const { Comment, User, Scam } = require('../models');

// 获取评论列表
exports.getComments = async (req, res) => {
  try {
    const { scamId } = req.params;
    const { page = 1, limit = 10 } = req.query;
    const offset = (page - 1) * limit;

    // 获取一级评论
    const { count, rows } = await Comment.findAndCountAll({
      where: {
        scamId,
        parentId: null
      },
      include: [
        {
          model: User,
          as: 'author',
          attributes: ['id', 'username']
        },
        {
          model: Comment,
          as: 'replies',
          include: [
            {
              model: User,
              as: 'author',
              attributes: ['id', 'username']
            }
          ],
          order: [['createdAt', 'ASC']]
        }
      ],
      order: [['createdAt', 'DESC']],
      limit: parseInt(limit),
      offset: parseInt(offset)
    });

    res.json({
      comments: rows,
      total: count,
      currentPage: parseInt(page),
      totalPages: Math.ceil(count / limit)
    });
  } catch (error) {
    res.status(500).json({
      message: '获取评论失败',
      error: error.message
    });
  }
};

// 创建评论
exports.createComment = async (req, res) => {
  try {
    const { content, parentId } = req.body;
    const { scamId } = req.params;

    // 检查骗子信息是否存在
    const scam = await Scam.findByPk(scamId);
    if (!scam) {
      return res.status(404).json({
        message: '信息不存在'
      });
    }

    // 如果是回复评论，检查父评论是否存在
    if (parentId) {
      const parentComment = await Comment.findByPk(parentId);
      if (!parentComment) {
        return res.status(404).json({
          message: '父评论不存在'
        });
      }
    }

    const comment = await Comment.create({
      content,
      scamId,
      userId: req.user.id,
      parentId,
      status: 'approved'
    });

    // 更新评论数
    await scam.increment('commentCount');

    res.status(201).json({
      message: '评论成功',
      comment
    });
  } catch (error) {
    res.status(500).json({
      message: '评论失败',
      error: error.message
    });
  }
};

// 更新评论状态
exports.updateCommentStatus = async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;

    const comment = await Comment.findByPk(id);
    if (!comment) {
      return res.status(404).json({
        message: '评论不存在'
      });
    }

    await comment.update({ status });

    res.json({
      message: '更新成功',
      comment
    });
  } catch (error) {
    res.status(500).json({
      message: '更新失败',
      error: error.message
    });
  }
};

// 删除评论
exports.deleteComment = async (req, res) => {
  try {
    const comment = await Comment.findByPk(req.params.id);
    if (!comment) {
      return res.status(404).json({
        message: '评论不存在'
      });
    }

    // 检查权限
    if (comment.userId !== req.user.id && req.user.role !== 'admin') {
      return res.status(403).json({
        message: '没有权限删除此评论'
      });
    }

    // 更新评论数
    await comment.scam.decrement('commentCount');

    await comment.destroy();

    res.json({
      message: '删除成功'
    });
  } catch (error) {
    res.status(500).json({
      message: '删除失败',
      error: error.message
    });
  }
}; 